package com.l.web.service.system.role;

import com.l.web.service.KeyUpdate;
import com.l.web.service.ResponseCode;
import org.l.qiao.file.Limit;
import org.l.qiao.search.Query;
import org.l.qiao.search.Update;
import com.l.web.service.ResponseInfo;
import com.l.web.service.ServiceSupport;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

public class RoleUpdateService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(RoleUpdateService.class);
    private RoleDAO roleDAO;

    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    public String execute() {
        String type = form.getString("type");
        if ("limit".equals(type)) {
            return limit();
        } else {
            return update();
        }
    }

    private String update() {
        KeyUpdate keyUpdate = this.getKeyUpdate(Role.class);
        LOGGER.debug("修改信息信息：" + keyUpdate);
        if (keyUpdate.check()) {
            int result = ResponseCode.FINISH;
            try {
                if ("LIMIT".equals(keyUpdate.getName())) {
                    result = updateLimit(keyUpdate);
                } else {
                    roleDAO.update(keyUpdate);
                }
            } catch (Exception e) {
                result = ResponseCode.FAILURE;
                LOGGER.error("修改异常[" + keyUpdate + "]：" + e);
            }
            ResponseInfo msg = new ResponseInfo(result);
            out(msg);
        } else {
            LOGGER.error("非法修改信息：" + keyUpdate);
            error(404);
        }
        return NONE;
    }

    private int updateLimit(KeyUpdate keyUpdate) throws Exception {
        Query query = new Query();
        query.idEQ(keyUpdate.getId());
        Update update = new Update(keyUpdate.getKey(), parseMap(keyUpdate));
        roleDAO.updateSet(query, update);
        return ResponseCode.FINISH;
    }

    private Map parseMap(KeyUpdate keyUpdate) {
        Map limitMap = new HashMap();
        try {
            JSONObject jsonValue = new JSONObject(keyUpdate.getValue());
            Iterator<String> iterator = jsonValue.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                JSONArray array = jsonValue.getJSONArray(key);
                List<String> page = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    page.add(array.getString(i));
                }
                limitMap.put(key, page);
            }
        } catch (Exception e) {
            LOGGER.error("错误权限值：" + e + "\n" + keyUpdate);
        }
        return limitMap;
    }

    private String limit() {
        Limit limit = new Limit();
        if (limit.load()) {
            context.put("limitConfig", limit.getLimit());
        }
        return "limit";
    }
}
